package com.magicode.screen.settingutil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppContext;
import com.magicode.screen.R;
import com.magicode.screen.api.remote.MgcApi;
import com.magicode.screen.bean.User;
import com.magicode.screen.util.FileUtil;
import com.magicode.screen.util.ImageUtils;
import com.magicode.screen.util.StringUtils;

import org.apache.http.Header;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 个人中心（用户头像）
 */
public class UserHeadPicUtil extends  Activity{
    private Uri origUri;
    private Uri cropUri;
    private File protraitFile;
    private Bitmap protraitBitmap;
    private String protraitPath;
    private boolean isChangeFace = false;
    private String theLarge;
    private final static int CROP = 200;
    private String userHeadPic;
    private final static String FILE_SAVEPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/magicode/Portrait/";
    private Activity context;
    public UserHeadPicUtil(Activity context){
        this.context=context;
    }



    public static final int ACTION_TYPE_PHOTO = 0;
    public static final int ACTION_TYPE_ALBUM = 1;


    public String goToSelectPicture(int position) {
        switch (position) {
            case ACTION_TYPE_PHOTO:
                startTakePhoto();
                break;
            case ACTION_TYPE_ALBUM:
                startImagePick();
                break;
            default:
                break;
        }
        return userHeadPic;
    }
    /**
     * 上传新照片
     */
    private void uploadNewPhoto() {
        // 获取头像缩略图
        if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
            protraitBitmap = ImageUtils
                    .loadImgThumbnail(protraitPath, 200, 200);
        } else {
            Toast.makeText(context, R.string.photo_faile, Toast.LENGTH_LONG).show();
        }
        if (protraitBitmap != null) {

            try {
                MgcApi.updateMyPortrait(AppContext.getInstance().getLoginUid(), protraitFile,
                        new AsyncHttpResponseHandler() {

                            @Override
                            public void onSuccess(int arg0, Header[] arg1, byte[] arg2)
                            {
                                try{
                                    ObjectMapper mapper = new ObjectMapper();
                                    User user = mapper.readValue(arg2, User.class);
                                    if (user.getStatus().equals("99")) {
                                        // 显示新头像
//                                    mUserFace.setImageBitmap(protraitBitmap);
                                        isChangeFace = true;
                                        userHeadPic=user.getPicNormalPath();
                                        AppContext.getInstance().saveUserInfo(user);
                                        Toast.makeText(context, R.string.photo_update_success, Toast.LENGTH_LONG).show();
                                    } else {
                                        Toast.makeText(context,user.getMessage(), Toast.LENGTH_LONG).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    onFailure(arg0, arg1, arg2, e);
                                }
                            }

                            @Override
                            public void onFailure(int arg0, Header[] arg1,
                                                  byte[] arg2, Throwable arg3) {
                                Toast.makeText(context, R.string.photo_update_faile, Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onFinish() {

                            }
                        });
            } catch (FileNotFoundException e) {
                Toast.makeText(context, R.string.photo_faile, Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 选择图片裁剪
     *
     */
    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            context.startActivityForResult(Intent.createChooser(intent, R.string.choice_photo+""),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            context.startActivityForResult(Intent.createChooser(intent, R.string.choice_photo+""),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        }
    }

    private void startTakePhoto() {
        Intent intent;
        // 判断是否挂载了SD卡
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/magicode/Camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (StringUtils.isEmpty(savePath)) {
            Toast.makeText(context,R.string.savephoto_sd_mount, Toast.LENGTH_LONG).show();
            return;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String fileName = "osc_" + timeStamp + ".jpg";// 照片命名
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        origUri = uri;

        theLarge = savePath + fileName;// 该照片的绝对路径
        try {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            context.startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
        }catch (Exception e){
            Toast.makeText(context,R.string.camera_authority, Toast.LENGTH_LONG).show();
        }
    }

    // 裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            Toast.makeText(context,R.string.sd_mount, Toast.LENGTH_LONG).show();
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath)) {
            thePath = ImageUtils.getAbsoluteImagePath(context, uri);
        }
        String ext = FileUtil.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "osc_crop_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        cropUri = Uri.fromFile(protraitFile);
        return this.cropUri;
    }

    /**
     * 拍照后裁剪
     *
     * @param data
     *            原始图片
     *            裁剪后图片
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        context.startActivityForResult(intent,
                ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode,
                                 final Intent imageReturnIntent) {
        if (resultCode != Activity.RESULT_OK)
            return;

        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
                startActionCrop(origUri);// 拍照后裁剪
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
                startActionCrop(imageReturnIntent.getData());// 选图后裁剪
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
                uploadNewPhoto();
                break;
        }
    }
    @Override
    public void onBackPressed() {
         super.onBackPressed();
    }
}
